#!/bin/bash
function install_nexus() {
    echo "安装Nexus" >>$logs_file
    rm -rf /tmp/.nexus.err.info
    nexusHome="$workHome/packages/nexus"
    nexusoPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$nexusoPid" ];then
        whiptail --backtitle "Author: Elvis" --title "警告" --msgbox "系统已经存在正在运行的Nexus请停止并卸载后继续！" 10 60
        sleep 0.10
        return 1
    fi
    whiptail --backtitle "Author: Elvis" --title "提示" --msgbox  \
"安装Nexus前，请确认已安装JDK，Nexus与JDK对应关系如下\n\
* 2.0-2.11.1：     Java 7\n\
* 2.11.2-2.13.0:   建议Java8，也可用Java 7u79以后版本\n\
* 2.14.0-2.14.10： 推荐Java 8，JAVA 7未测试\n\
* 2.14.11+：        JAVA 8\n
更详细的版本要求，请参见使用帮助" 14 60
    
    nexusVer=$(whiptail --backtitle "Author: Elvis" --title "版本选择" --radiolist --nocancel \
    "请选择要安装的Nexus版本？" 12 60 5 \
    "2.13.0" "需要JAVA 7            " ON \
    "2.14.10" "建议Java 8        " OFF \
    "2.14.17" "需要JAVA 8" OFF \
    "3.23.0"  "需要JAVA 8" OFF \
    "Other"  "自定义版本" OFF 3>&1 1>&2 2>&3)
    
    if [ "$nexusVer" == "Other" ];then
        nexusVer=$(whiptail --backtitle "Author: Elvis" --title "NEXUS版本" --inputbox --nocancel \
    "请输入要安装的Nexus版本，格式为X.XXX.X" 10 60 3>&1 1>&2 2>&3)
    fi
    nexusVer=`echo $nexusVer`
    nexusPack=`ls $nexusHome 2>/dev/null|grep "nexus-$nexusVer.*.tar.gz"|head -n1`
    if [ -z "$nexusPack" ];then
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "packages/nexus目录未找到要安装的nexus版本！" 10 60
        sleep 0.10
        return 1
    fi
    
    nexusPath=$(whiptail --backtitle "Author: Elvis" --title "Nexus配置" --inputbox --nocancel \
    "请输入Nexus安装目录" 10 60 "/usr/local/nexus" 3>&1 1>&2 2>&3)
    nexusPath=${nexusPath:-/usr/local/nexus}
    nexusPath=`echo $nexusPath`
    nexusPath=${nexusPath%/}
    isNull=`ls $nexusPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "继续" --no-button "退出" --yesno "给出的Nexus安装目录非空，继续安装会删除已有数据！\n\n是否继续安装？" 10 60
        if [ "$?" != "0" ];then
         sleep 0.10
         return 1
        fi
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    nexusPort=
    while [[ ! "$nexusPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        nexusPort=$(whiptail --backtitle "Author: Elvis" --title "Nexus配置" --inputbox --nocancel \
        "请输入Nexus监听端口，注意端口是否被占用" 10 60 "8081" 3>&1 1>&2 2>&3)
        if [[ ! "$nexusPort" =~ ^[1-9][0-9]+$ ]];then
             whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "nexus端口只能为两位及以上且不以0开头的数字组成，请重新输入！" 10 60
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${nexusPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "nexus监听端口已被使用，请重新输入！" 8 60
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    nexusPort=${nexusPort:-8081}
    nexusPort=`echo $nexusPort`
    nexusUser=
    nexusUser=$(whiptail --backtitle "Author: Elvis" --title "Nexus配置" --inputbox --nocancel \
    "请输入Nexus运行用户" 10 60 "root" 3>&1 1>&2 2>&3)
    nexusUser=${nexusUser:-root}
    nexusUser=`echo $nexusUser`

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel \
    "系统未找到到java命令，请手动输入java命令路径" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
    else
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "确定" --no-button "修改" --yesno "系统检测到java命令路径为$javaPath\n\n如果正确请确认，不正确请修改." 10 60
        if [ "$?" != "0" ];then
          javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel "请输入java命令位置" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
        fi
    fi
    javaPath=`echo $javaPath`
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    if [ -z "$javaOut" ];then
        msg="设置的java命令路径错误，执行java -version命令错误，退出nexus安装"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "$msg" 10 70
        sleep 0.10
        return 1
    fi
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    
    whiptail --backtitle "Author: Elvis" --title "Nexus安装信息汇总" --yesno "\nNexus版本：$nexusVer\nNexus路径：$nexusPath\nNexus端口：$nexusPort\nNexus运行用户：$nexusUser\nJAVA命令：$javaPath\nJDK版本信息：$java_version\n\nYes以继续安装，No退出Nexus安装" 15 70
    if [ "$?" != "0" ];then
        sleep 0.10
        return 1
    fi
    nexus_MainVer=`echo $nexusVer|awk -F"." '{print $1}'`
    if [ "$nexus_MainVer" == "3" ];then
        reqUrl="http://$ipaddr:$nexusPort/"
        console_cmd="nexus run"
    else
        reqUrl="http://$ipaddr:$nexusPort/nexus/"
        console_cmd="nexus console"
    fi
    nexusPw=`strings /dev/urandom |grep -o '[[:alnum:]_%@!]'|head -n 25|tr -d '\n'`
    
    {
    cd $nexusHome
    echo 1
    sleep 0.30
    msg="创建Nexus运行用户"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n30\n$msg\nXXX"
    echo 30
    isExistU=`cat /etc/passwd|grep "^$nexusUser:"`
    if [ -z "$isExistU" ];then
        /usr/sbin/useradd $nexusUser >>$logs_file 2>&1
        echo "$nexusPw"|passwd --stdin $nexusUser >>$logs_file 2>&1
    else
        if [ "$nexusUser" != "root" ];then
         /usr/sbin/usermod -s /bin/bash $nexusUser >>$logs_file 2>&1 
         echo "$nexusPw"|passwd --stdin $nexusUser >>$logs_file 2>&1
        fi
    fi
    
    msg="开始安装Nexus"
    rm -rf $nexusPath
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n60\n$msg\nXXX"
    echo 60
    mkdir -p $nexusPath >/dev/null 2>&1
    chown -R $nexusUser:$nexusUser $nexusPath >/dev/null 2>&1
    tar zxf $nexusPack -C $nexusPath >/dev/null 2>>$logs_file
    if [ "$?" != "0" ];then
        msg="Nexus安装包损坏，解压失败"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n65\n$msg\nXXX"
        echo "$msg" >/tmp/.nexus.err.info
        echo 65
        sleep 3
        return 1
    fi
        
    msg="修改Nexus配置"
    nexusBinPath="$nexusPath/`ls $nexusPath|grep nexus-$nexusVer`"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n80\n$msg\nXXX"
    echo 80
    sleep 1
    real_javaPath=$(readlink -f $javaPath)
    javaHome=${real_javaPath%%/bin/*}
    
    if [ "$nexus_MainVer" == "3" ];then
        sed -i "s/^[# ]*run_as_user=.*/run_as_user=$nexusUser/g" $nexusBinPath/bin/nexus >>$logs_file 2>&1
        sed -i "/# INSTALL4J_JAVA_HOME_OVERRIDE=/a INSTALL4J_JAVA_HOME_OVERRIDE=$javaHome" $nexusBinPath/bin/nexus >>$logs_file 2>&1
        sed -i "s/^application-port=.*/application-port=$nexusPort/g" $nexusBinPath/etc/nexus-default.properties >>$logs_file 2>&1
    else
        sed -i "s/^[# ]*RUN_AS_USER=.*/RUN_AS_USER=$nexusUser/g" $nexusBinPath/bin/nexus >>$logs_file 2>&1
        sed -i "s#^wrapper.java.command=.*#wrapper.java.command=$javaPath#g" $nexusBinPath/bin/jsw/conf/wrapper.conf >>$logs_file 2>&1
        sed -i "s/^application-port=.*/application-port=$nexusPort/g" $nexusBinPath/conf/nexus.properties >>$logs_file 2>&1
    fi
    
    msg="添加nexus服务脚本，并设置开机启动"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n85\n$msg\nXXX"
    echo 85
    systemctl --version >/dev/null 2>&1
    if [ "$?" != "0" ];then
        cat >/etc/init.d/nexus<<EOF
#chkconfig:2345 20 90
#description:nexus
#processname:nexus
EXEC=$nexusBinPath/bin/nexus
case \$1 in
start) 
    \$EXEC start
    ;;
stop)
    \$EXEC stop
    ;;
status)
    \$EXEC status
    ;;
restart)
    \$EXEC restart
    ;;
dump)
    \$EXEC dump
    ;;
console)
    \$EXEC console
    ;;
*)
   echo "Usage: nexus console|start|stop|restart|status|dump"
   ;;
esac
EOF
        chmod +x /etc/init.d/nexus >>$logs_file 2>&1
        /sbin/chkconfig --add nexus >>$logs_file 2>&1
        /sbin/chkconfig nexus on >>$logs_file 2>&1
    else
        cat >/etc/systemd/system/nexus.service<<EOF
[Unit]
Description=nexus service
After=network.target
  
[Service]
Type=forking
LimitNOFILE=65536
ExecStart=$nexusBinPath/bin/nexus start
ExecStop=$nexusBinPath/bin/nexus stop
User=$nexusUser
Restart=on-abort
TimeoutSec=600
  
[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload >>$logs_file 2>&1
        systemctl enable nexus >>$logs_file 2>&1
    fi

    msg="启动Nexus"
    chown -R $nexusUser:$nexusUser $nexusPath >/dev/null 2>&1
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n90\n$msg\nXXX"
    echo 90
    sleep 1
    systemctl start nexus >>$logs_file 2>&1 || service nexus start >>$logs_file 2>&1
    echo -e "XXX\n95\n等待Nexus启动中.....\nXXX"
    echo 95
    n=1
    curl --fail $reqUrl >/dev/null 2>&1
    exitstatus="$?"
    while [ "$exitstatus" != "0" ]
    do
      echo "等待nexus启动 $n" >>$logs_file
      echo -e "XXX\n96\n等待Nexus启动$n/65\nXXX"
      echo 96
      let n+=1
      sleep 1
      curl --fail $reqUrl >/dev/null 2>&1
      exitstatus="$?"
      if [ $n -gt 20 ];then
         nexusRPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
         if [ -z "$nexusRPid" ];then
             break
         fi
      fi
      if [ $n -gt 65 ];then
         break
      fi
    done
      
    echo -e "XXX\n100\ndone！！！\nXXX"
    echo 100
    sleep 1 
    } | whiptail --backtitle "Author: Elvis" --title "安装Nexus" --gauge " " 6 60 0
    if [ -f /tmp/.nexus.err.info ];then
        errinfo=`cat /tmp/.nexus.err.info` >>$logs_file
        rm -rf /tmp/.nexus.err.info
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "Nexus安装失败！\n$errinfo" 10 70
        sleep 0.10
        return 1
    fi
    #判断是否启动
    sleep 0.30
    UserUID=`cat /etc/passwd|grep "^$nexusUser:"|awk -F":" '{print $3}'`
    pass_info=
    if [ -n "$UserUID" -a "$nexusUser" != "root" ];then
        pass_info="$nexusUser用户密码为：$nexusPw，请牢记或修改！"
    fi
    #nexus3.17后默认admin密码为随机
    passwdFile=`find $nexusPath/sonatype-work/ -name "admin.password" -type f`
    [[ $passwdFile ]] && adminPw=`cat $passwdFile` || adminPw="admin123"
    nexusUPid=`ps aux -u $UserUID|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    nexusPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$nexusPid" ];then
        if [ -n "$nexusUPid" ];then
          echo "Nexus安装成功" >>$logs_file
          whiptail --backtitle "Author: Elvis" --title "消息" --msgbox "Nexus安装成功！！！\n访问地址：$reqUrl\n默认管理用户密码为：admin/$adminPw\n$pass_info" 13 80
        else
          echo "Nexus安装存在问题，并未按指定用户运行，请检查配置文件\n$pass_info" >>$logs_file
          whiptail --backtitle "Author: Elvis" --title "警告" --msgbox "Nexus程序未按指定用户运行，请检查配置文件！" 13 80
        fi
    else
        echo "Nexus安装失败" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "Nexus安装失败！！！\n请使用$console_cmd模式启动以排查错误." 10 70
    fi
    sleep 0.30 
}